package com.baiyang.server.service.book.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baiyang.server.model.PageEntity;
import com.baiyang.server.model.book.*;
import com.baiyang.server.service.book.*;
import com.baiyang.server.service.impl.BaseServiceImpl;
import com.baiyang.server.service.transaction.OrdersService;
import com.baiyang.server.tools.DataTool;
import com.baiyang.server.tools.Letter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baiyang.server.dao.book.BookDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author XVX
 * BY: @Primary 注解帮助生命@Autowired优先注入的实列
 */
@Service	
public class BookServiceImpl extends BaseServiceImpl<BookDao, Book> implements BookService{
    @Autowired
    private BookDao bookDao = null;
    @Autowired
    private RelBookTypeService relBookTypeService = null;
    @Autowired
    private ResourcesService resourcesService = null;
    @Autowired
    private StockService stockService = null;
    @Autowired
    private BookTypeService bookTypeService = null;
    @Autowired
    private OrdersService ordersService = null;

    @Transactional
    @Override
    public void insertBook(Book book, Letter<String> letter) {
        //判断书籍是否重名
        Book item = new Book();
        item.setBookName(book.getBookName());
        item.setPressId(book.getPressId());
        List<RelBookType> relBookTypes = new ArrayList<>();
        //插入书籍类型
        book.getTypeIds().forEach(e->{
            RelBookType relBookType = new RelBookType();
            relBookType.setId(DataTool.createUUID());
            relBookType.setBookId(book.getId());
            relBookType.setType(e);
            relBookType.setCreateBy(book.getCreateBy());
            relBookTypes.add(relBookType);
        });
        relBookTypeService.insertBatch(relBookTypes);
        //插入图片信息
        int showIndex = 0;
        for (Resources e:book.getResources()){
            e.setId(DataTool.createUUID());
            e.setCreateBy(book.getCreateBy());
            e.setRelationId(book.getId());
            e.setRelationType("book-title-head");
            e.setShowIndex(showIndex++);
        }
        showIndex = 0;
        for (Resources e:book.getDetailResources()){
            e.setId(DataTool.createUUID());
            e.setCreateBy(book.getCreateBy());
            e.setRelationId(book.getId());
            e.setRelationType("book-title-detail");
            e.setShowIndex(showIndex++);
        }
        List<Resources> resources = new ArrayList<>();
        resources.addAll(book.getResources());
        resources.addAll(book.getDetailResources());
        if(DataTool.isBlank(resources)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            letter.setResult("FAIL");
            letter.setDetail("书籍信息添加失败");
            return ;
        }
        resourcesService.insertBatch(resources);
        //插入库存信息
        Stock stock = new Stock();
        stock.setBookId(book.getId());
        stock.setStock(0d);
        stockService.insert(stock);
        // 将用户自定义书籍信息以XML的形式存储到数据库中
        String xmlPath = createXML(book.getDetails());
        if(xmlPath == null && !DataTool.isBlank(book.getDetails())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            letter.setResult("FAIL");
            letter.setDetail("书籍信息添加失败");
            return ;
        }
        book.setDetailsPath(xmlPath);
        bookDao.insert(book);
        letter.setResult("SUCCESS");
        letter.setDetail("插入成功");
    }

    @Override
    public Book selectOneBook(Book book) {
        book = bookDao.selectOne(book);
        if(book == null){
            return null;
        }
        // 设置类型信息
        RelBookType relBookType = new RelBookType();
        relBookType.setBookId(book.getId());
        List<RelBookType> relBookTypes = relBookTypeService.selectList(relBookType);
        List<String> typeIds = new ArrayList<>();
        relBookTypes.forEach(e->{
            typeIds.add(e.getType());
        });
        List<BookType> bookTypes = bookTypeService.selectByIds(typeIds);
        book.setBookTypes(bookTypes);
        book.setTypeIds(typeIds);
        //获取资源信息
        Resources resources = new Resources();
        resources.setRelationType("book-title-head");
        resources.setRelationId(book.getId());
        List<Resources> list = resourcesService.selectList(resources);
        book.setResources(list);
        resources.setRelationType("book-title-detail");
        list = resourcesService.selectList(resources);
        book.setDetailResources(list);
        //获取详情信息
        book.setDetails(getXML(book.getDetailsPath()));
        return book;
    }

    @Override
    public PageEntity<Book> getPages(JSONObject object) {
        List<Book> books = bookDao.getPages(object);
        books.forEach(e->{
            JSONArray xml = getXML(e.getDetailsPath());
            e.setDetails(xml);
            // 设置月销售数量
            int num = ordersService.getMonthlySales(e.getId());
            e.setMonthlySales(num);
        });
        PageEntity<Book> pageEntity = new PageEntity<>();
        pageEntity.setDatas(books);
        pageEntity.setCount(bookDao.getNum(object));
        return pageEntity;
    }


    @Transactional
    @Override
    public void updateBook(Book book, Letter<String> letter) {
        // 删除类型关联
        relBookTypeService.deleteByBookId(book.getId());
        // 删除资源关联
        resourcesService.deleteByBookId(book.getId());
        // 删除XML文件
        File file = new File(filePath + File.separator + book.getDetailsPath());
        if(file.exists()) {
            file.delete();
            System.out.println("删除成功");
        }
        //插入书籍类型
        List<RelBookType> relBookTypes = new ArrayList<>();
        book.getTypeIds().forEach(e->{
            RelBookType relBookType = new RelBookType();
            relBookType.setId(DataTool.createUUID());
            relBookType.setBookId(book.getId());
            relBookType.setType(e);
            relBookType.setCreateBy(book.getCreateBy());
            relBookTypes.add(relBookType);
        });
        relBookTypeService.insertBatch(relBookTypes);
        //插入图片信息
        book.getResources().forEach(e->{
            e.setId(DataTool.createUUID());
            e.setCreateBy(book.getCreateBy());
            e.setRelationId(book.getId());
            e.setRelationType("book-title-head");
        });
        book.getDetailResources().forEach(e->{
            e.setId(DataTool.createUUID());
            e.setCreateBy(book.getCreateBy());
            e.setRelationId(book.getId());
            e.setRelationType("book-title-detail");
        });
        List<Resources> resources = new ArrayList<>();
        resources.addAll(book.getResources());
        resources.addAll(book.getDetailResources());
        if(DataTool.isBlank(resources)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            letter.setResult("FAIL");
            letter.setDetail("书籍信息添加失败");
            return ;
        }
        resourcesService.insertBatch(resources);
        // 将用户自定义书籍信息以XML的形式存储到数据库中
        String xmlPath = createXML(book.getDetails());
        if(xmlPath == null && !DataTool.isBlank(book.getDetails())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            letter.setResult("FAIL");
            letter.setDetail("书籍信息添加失败");
            return ;
        }
        book.setDetailsPath(xmlPath);
        letter.setResult("SUCCESS");
        letter.setDetail("修改成功");
        bookDao.updateById(book);
    }


    /**上传地址*/
    @Value("${file.upload.path}")
    private String filePath;

    /**
     * 获取XML文件信息
     * @param path
     * @return
     */
    private JSONArray getXML(String path){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        List<JSONObject> list = new ArrayList<>();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document d = builder.parse(filePath + File.separator + path);
            NodeList nList = d.getElementsByTagName("detail");
            for (int i = 0; i <nList.getLength() ; i++) {
                Node node = nList.item(i);
                JSONObject object = new JSONObject();
                object.put("title",node.getAttributes().getNamedItem("title").getNodeValue());
                object.put("content",node.getFirstChild().getNodeValue());
                list.add(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list==null?null:JSONArray.parseArray(JSON.toJSONString(list));
    }

    /**
     * 生成XML文件
     * @param array
     * @return
     */
    private String createXML(JSONArray array){
        String path = DataTool.sdf_ymd.format(new Date()) +
                File.separator +
               DataTool.createUUID() + ".xml";;
        try {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.newDocument();
            // 不显示standalone="no"
            document.setXmlStandalone(true);
            Element root = document.createElement("root");
            document.appendChild(root);
            array.forEach(e->{
                Map<String,String> item = (Map<String, String>) e;
                Element element = document.createElement("detail");
                element.setTextContent(item.get("content"));
                element.setAttribute("title",item.get("title"));
                root.appendChild(element);
            });
            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(new File(filePath + File.separator + path)));
            System.out.println("生成XML成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("生成XML失败");
            return null;
        }
        return path;
    }
}
